package com.bing.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bing.common.constant.CommonConstant;
import com.bing.common.exception.BusinessException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;

/**
 * @Description 文件工具
 * @Author Bing
 * @Date 2025/5/13 17:08
 */
public class FileTools {
    /**
     * 下载文件
     * @param path
     */
    public static ResponseEntity<Resource> download(String path) {
        File file = FileUtil.file(path);
        checkFile(file);
        Resource resource = new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
        return ResponseEntity.ok().headers(headers).body(resource);
    }

    /**
     * 校验文件
     * @param file
     * @return
     * @throws IOException
     */
    private static void checkFile(File file){
        if(ObjectUtil.isNull(file)) {
            BusinessException.throwBusException("文件不存在");
        }
        if(!file.exists()){
            BusinessException.throwBusException("文件不存在");
        }
        if(!file.isFile()){
            BusinessException.throwBusException("不是有效文件");
        }
        if(file.length() <= CommonConstant.NUM_ZERO){
            BusinessException.throwBusException("不是有效文件");
        }
    }
}